﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using ARchGL.Declaration.Platform.Domain.Entities;
using ARchGL.Declaration.Platform.Service;
using ARchGL.Declaration.Platform.Service.Dtos;
using Newtonsoft.Json;
using TDF.Core.Configuration;
using TDF.Core.Exceptions;
using TDF.Core.Models;

namespace ARchGL.Declaration.Platform.Web.Controllers.Apis
{
    /// <summary>
    /// 报表相关接口
    /// </summary>
    public partial class ProjectController : ApiControllerBase
    {
        #region 报表提供

        /// <summary>
        /// 待审核申请信息-统计
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult WaitReviewReport([FromBody]ProjectAreaIdCriteria criteria)
        {
            var result = ProjectService.WaitReviewReport(criteria.AreaId);
            return Success(result);
        }

        /// <summary>
        /// 月报表查询时间，只有返回时间内才有数据
        /// </summary>
        /// <returns></returns>
        public ApiResult QueryMonthListReport()
        {
            var list = new List<DateTime>
            {
                DateTime.Parse("2019-01-31"),
                DateTime.Parse("2018-12-31"),
                DateTime.Parse("2018-11-30"),
                DateTime.Parse("2018-10-31"),
            };
            return Success(list);
        }

        /// <summary>
        /// 月报统计
        /// </summary>
        /// <param name="from">筛选条件</param>
        /// <returns></returns>
        public ApiResult MonthReport([FromBody]MonthReportFrom from)
        {
            if (!DateTime.TryParse(from.Date, out var date))
                throw new KnownException("日期格式错误");

            var result = ProjectService.MonthReport(date, from.AreaId);
            return Success(result);
        }

        /// <summary>
        /// 下载月报统计
        /// </summary>
        /// <param name="from">筛选条件</param>
        /// <returns></returns>
        public HttpResponseMessage DownMonthReport([FromBody]MonthReportFrom from)
        {
            if (!DateTime.TryParse(from.Date, out var date))
                throw new KnownException("日期格式错误");

            var result = ProjectService.MonthReport(date, from.AreaId);
            var fileName = date.ToString("yyyy年截止MM月") + "统计报表.xls";

            var dt = new DataTable(fileName);
            var columns = new List<string> { "序号", "单位", "人员账号", "月份", "总项目数", "未验收项目", "验收中项目", "已验收项目", "总工程数", "未验收工程", "验收中工程", "已验收工程", "BIM已认定", "元素已验收" };

            for (int i = 0; i < columns.Count; i++)
            {
                var item = columns[i];
                var type = i > 3 ? typeof(int) : typeof(string);
                dt.Columns.Add(item, type);
            }

            for (int i = 0; i < result.Count; i++)
            {
                var item = result[i];
                var dr = dt.NewRow();
                dr[columns[0]] = i + 1;
                dr[columns[1]] = item.Name;
                dr[columns[2]] = item.Number;
                dr[columns[3]] = item.Month;
                for (int c = 0; c < item.TotalArray.Length; c++)
                {
                    dr[columns[4 + c]] = item.TotalArray[c];
                }
                dt.Rows.Add(dr);
            }

            var lastdr = dt.NewRow();
            lastdr[columns[0]] = "总计";
            lastdr[columns[1]] = "";
            lastdr[columns[2]] = "";
            lastdr[columns[3]] = "";

            lastdr[columns[4]] = Sum(dt, columns[4]);
            lastdr[columns[5]] = Sum(dt, columns[5]);
            lastdr[columns[6]] = Sum(dt, columns[6]);
            lastdr[columns[7]] = Sum(dt, columns[7]);
            lastdr[columns[8]] = Sum(dt, columns[8]);
            lastdr[columns[9]] = Sum(dt, columns[9]);
            lastdr[columns[10]] = Sum(dt, columns[10]);
            lastdr[columns[11]] = Sum(dt, columns[11]);
            lastdr[columns[12]] = Sum(dt, columns[12]);
            lastdr[columns[13]] = Sum(dt, columns[13]);
            dt.Rows.Add(lastdr);

            var path = new Configs().GetValue("DownloadPath") + "/" + from.AreaId + "_" + fileName;
            NPOIHelper.Export(dt, $"{date.ToString("yyyy年截止MM月")}统计报表", path);


            var fileinfo = new FileInfo(path);
            var stream = new FileStream(path, FileMode.OpenOrCreate);
            var response = new HttpResponseMessage();

            //response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("月报表.xls", Encoding.UTF8));
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                Name = "foo",
                FileName = "foo.txt",
                FileNameStar = "foo.txt",
                DispositionType = "attachment",
            };

            return response;
        }

        private int Sum(DataTable dt, string columnName)
        {
            return int.Parse(dt.Compute($"sum({columnName})", "true").ToString());
        }

        /// <summary>
        /// 已报未报工程-统计
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult ProjectDeclarationReport([FromBody]ProjectAreaIdCriteria criteria)
        {
            var result = ProjectService.ProjectDeclarationReport(criteria.AreaId);
            return Success(result);
        }

        /// <summary>
        /// 已报工程中审核通过与未通过-统计
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult ProjectFileReport([FromBody]ProjectAreaIdCriteria criteria)
        {
            var result = ProjectService.ProjectFileReport(criteria.AreaId);
            return Success(result);
        }

        /// <summary>
        /// 已报工程中提交文件数-统计
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult ProjectSubmitReport([FromBody]ProjectAreaIdCriteria criteria)
        {
            var result = ProjectService.ProjectSubmitReport(criteria.AreaId);
            return Success(result);
        }

        /// <summary>
        /// 已报工程中审核文件数-统计
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult ProjectReviewReport([FromBody]ProjectAreaIdCriteria criteria)
        {
            var result = ProjectService.ProjectReviewReport(criteria.AreaId);
            return Success(result);
        }

        /// <summary>
        /// 工程地图-统计
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult ProjectMapReport([FromBody]ProjectAreaIdCriteria criteria)
        {
            var list = ProjectService.GetProjectFirstCategoryOverview(new ProjectOverviewCriteria
            {
                PageIndex = 1,
                PageSize = 10000,
                AreaId = criteria.AreaId,
                IsChildProject = true,
            });

            var result = new List<ProjectMapReportDto>();
            foreach (var item in list.Rows)
            {
                result.Add(new ProjectMapReportDto
                {
                    Id = item.Id,
                    Name = item.Name,
                    Location = item.Location,
                    FirstCategoryStatus1 = item.FirstCategoryStatus1,
                    FirstCategoryStatus2 = item.FirstCategoryStatus2,
                    FirstCategoryStatus3 = item.FirstCategoryStatus3,
                    FirstCategoryStatus4 = item.FirstCategoryStatus4,
                });
            }
            return Success(result);
        }

        /// <summary>
        /// 单项申请状态-统计
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public ApiResult ProjectSubitemReport([FromBody]ProjectSubitemReportFrom from)
        {
            var result = ProjectService.ProjectSubitemReport(from.AreaId, from.Type);
            return Success(result);
        }

        #endregion
    }
}
